package com.unionServer.codecs;

import com.unionServer.models.GatewayMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: wangxinal
 * @time: 2022/1/8
 */
@Slf4j
public class UnionEncoder extends MessageToByteEncoder<GatewayMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, GatewayMessage msg, ByteBuf out) throws Exception {
        byte[] temp = mergeAllBytes(msg.getNumString().getBytes("ASCII"),msg.getByteMessage());
        out.writeBytes(temp);
//        out.writeBytes(msg.getByteArray());
    }
    public static byte[] mergeAllBytes(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }
}
